package com.qf.game.utils;

import com.qf.framwork.utils.PropertiesUtils;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * 发邮件的工具类
 *
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
public class MailUtils {

    /**
     * 发送邮件
     * @return
     */
    public static boolean sendMail(String to, String subject, String content){
        //1、创建Session - 使用properties对象
        Session session = Session.getDefaultInstance(PropertiesUtils.getPropertiesObj());
        //2、创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        //3、设置邮件
        try {
            //设置标题
            mimeMessage.setSubject(subject, "utf-8");
            //设置发送方
            mimeMessage.setFrom(new InternetAddress(PropertiesUtils.getProperties("mail.username"), "腾讯官方", "utf-8"));
            //设置收件方
            //Message.RecipientType.TO - 普通收件人
            //Message.RecipientType.CC - 抄送方
            //Message.RecipientType.BCC - 密送方
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            //设置内容
            mimeMessage.setText(content, "utf-8");
            //设置发送时间
            mimeMessage.setSentDate(new Date());
            //保存邮件信息
            mimeMessage.saveChanges();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        //4、通过session获取SMTP服务连接对象
        Transport transport = null;
        try {
            transport = session.getTransport();
            //连接服务器
            transport.connect(PropertiesUtils.getProperties("mail.username"), PropertiesUtils.getProperties("mail.password"));
            //发送邮件
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            //关闭连接
            if (transport != null) {
                try {
                    transport.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }

        return true;
    }
}
